package resource.handler;

import java.util.ArrayList;

import launch.SimpleTest;

import org.newdawn.slick.Color;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;
import org.xml.sax.helpers.DefaultHandler;

import dialog.ClockedDialog;
import dialog.DialogDeroulement;
import dialog.Replique;

/**
 * Parser SAX
 * @author Kent
 *
 */
public class DialogHandler extends DefaultHandler {

	private ArrayList<DialogDeroulement> l_dial;
	private int lastrep;
	
	public DialogHandler(ArrayList<DialogDeroulement> s){
		l_dial = s;
	}

	public void characters(char[] buffer, int start, int length) {
	}

	public void startElement(String uri, String name, String qName, Attributes attributes){
		
		if (qName.equals("dialogue")){
			l_dial.add(new DialogDeroulement(attributes.getValue("name")));
		};
		
		if (qName.equals("replique")){
			boolean once = (attributes.getValue("once")) != null;
			boolean exit = (attributes.getValue("exit")) != null;
			ArrayList<Replique> entree = new ArrayList<Replique>();
			String condition = attributes.getValue("condition");
			
			if(!condition.equals("")){
				if(condition.contains(",")){
					String[] conditions = condition.split(",");
					for(String s : conditions){
						entree.add(l_dial.get(l_dial.size()-1).getReplique(Integer.parseInt(s)));
					}
				}else{
					entree.add(l_dial.get(l_dial.size()-1).getReplique(Integer.parseInt(condition)));
				}
			}
			lastrep = Integer.parseInt(attributes.getValue("numero"));
			l_dial.get(l_dial.size()-1).AddReplique(new Replique(lastrep,once,exit,entree));
		};
		
		if (qName.equals("message")){
			ClockedDialog c = new ClockedDialog(attributes.getValue("contenu"), Color.decode(attributes.getValue("color")), new Color(1f,1f,1.0f,0.5f), Integer.parseInt(attributes.getValue("time")),Integer.parseInt(attributes.getValue("startAt")), SimpleTest.gc_manager.getGameCharacter(attributes.getValue("emetteur")));
			l_dial.get(l_dial.size()-1).getReplique(lastrep).addMessage(c);
		}
	}

	// When the parser encounters the end of an element, it calls this method
	public void endElement(String uri, String name, String qName){

	}

	/** This method is called when warnings occur */
	public void warning(SAXParseException exception) {
		System.err.println("WARNING: line " + exception.getLineNumber() + ": "
				+ exception.getMessage());
	}

	/** This method is called when errors occur */
	public void error(SAXParseException exception) {
		System.err.println("ERROR: line " + exception.getLineNumber() + ": "
				+ exception.getMessage());
	}

	/** This method is called when non-recoverable errors occur. */
	public void fatalError(SAXParseException exception) throws SAXException {
		System.err.println("FATAL: line " + exception.getLineNumber() + ": "
				+ exception.getMessage());
		throw (exception);
	}
}